package com.example.backend.service.impl;

import com.example.backend.common.api.ResultCode;
import com.example.backend.common.exception.BusinessException;
import com.example.backend.service.CaptchaService;
import com.example.backend.service.EmailService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 验证码服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CaptchaServiceImpl implements CaptchaService {
    
    private final EmailService emailService;
    private final StringRedisTemplate redisTemplate;
    
    // 验证码过期时间（分钟）
    private static final long EXPIRE_MINUTES = 5;
    // 验证码长度
    private static final int CODE_LENGTH = 6;
    // 验证码Redis key前缀
    private static final String CAPTCHA_KEY_PREFIX = "captcha:%s:%s";
    
    @Override
    public void sendCaptcha(String email, String type) {
        // 生成验证码
        String code = generateCode();
        
        // 保存到Redis
        String key = String.format(CAPTCHA_KEY_PREFIX, type, email);
        redisTemplate.opsForValue().set(key, code, EXPIRE_MINUTES, TimeUnit.MINUTES);
        
        // 发送验证码邮件
        try {
            Map<String, Object> variables = new HashMap<>();
            variables.put("code", code);
            emailService.sendTemplateMail(email, "验证码", "verification", variables);
        } catch (Exception e) {
            log.error("发送验证码失败", e);
            throw new BusinessException(ResultCode.SEND_CAPTCHA_ERROR);
        }
    }
    
    @Override
    public boolean verifyCaptcha(String email, String code, String type) {
        String key = String.format(CAPTCHA_KEY_PREFIX, type, email);
        String savedCode = redisTemplate.opsForValue().get(key);
        
        if (savedCode == null) {
            return false;
        }
        
        // 验证成功后删除验证码
        if (savedCode.equals(code)) {
            redisTemplate.delete(key);
            return true;
        }
        
        return false;
    }
    
    /**
     * 生成验证码
     */
    private String generateCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }
} 